import { Component, ViewChild, ViewChildren, OnInit, DoCheck } from '@angular/core';

import { NavController, ModalController, AlertController, Platform, VirtualScroll, Scroll, NavParams } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { StatusBar } from "@ionic-native/status-bar";

import {DomSanitizer} from '@angular/platform-browser';

import { Common } from "../../../providers/common";
import { Config } from "../../../providers/config";

import _ from "lodash";
import { Content } from 'ionic-angular';
import {IpmCirculateModal} from "../circulate/circulate.modal";
import {CashService} from "./cash.service";

@Component({
	selector: 'page-ipm-cash-detail',
	templateUrl: 'detail.html',
  providers: [CashService]
})
export class IpmCashDetailPage implements OnInit,DoCheck {
	moa_page_name: any = "IpmCashDetailPage";
  moa_page_explain: any = "现金流明细";

  ngOnInit() {

  }

  ngDoCheck() {
    this.setDataGridHeight();
  }

  @ViewChild(Content) content: Content;

  items = [0];

  // 列表数据
  listData: any = [];

  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

	hisDays = 20;
	baseValue = 1000;

	showQueryParams = false;
	showQueryCondition = true;

  maxDate = "";

  queryCondition = null;

  selectedFund = [];
  successFund = [];
  fundCode = "";

  @ViewChildren(VirtualScroll)
  virtualScrolls;

  @ViewChild(Scroll)
  rightScroll: Scroll;

  maxStartDate = "";
  minEndDate = "";

  selectedDate = [];

  showLoading = false;

  userInfo = null;

  showByLandscape = false;

  rowHeight = 0;
  contentWidth = 0;
  fundLeftHeight = 0;
  fundRightHeight = 0;
  fundRightMarginTop = 0;

  rotateClass = "";

  funds_right_scroll_x = "";
  funds_left_scroll_x = "";
  fundsContentClass = "";
  scrollContentMarginTop = "";

  params = null;
  isRedemption = false;
  disabledExistFullScreen = false;

	constructor(
		public navCtrl: NavController,
    public common: Common,
    public modalCtrl: ModalController,
    public alertCtrl: AlertController,
    public config: Config,
    public  plt: Platform,
    private sanitizer: DomSanitizer,
    public cashService: CashService,
    public storage: Storage,
    public navParams: NavParams,
    public statusBar: StatusBar
	) {

	  // console.log(this.formatNumberToAccountancy(_.toString(parseFloat("40.8").toFixed(2))));
    // this.maxDate = "2099-12-12";//this.common.getNowFormatDate();

    this.maxStartDate = this.common.getNowFormatDate();
    this.minEndDate =this.maxStartDate;

    this.initQueryCondition();

    this.params = this.navParams.get("params");
    this.isRedemption = this.navParams.get("isRedemption");

    let params_showByLandscape = this.navParams.get("showByLandscape");
    if (params_showByLandscape) {
      // this.statusBar.hide();
    }

    console.log("IpmCashDetailPage.params", this.params);

  }

  ionViewDidLoad() {
	  this.content.ionScroll.subscribe(($event: any) => {
	    this.setDataGridHeight();
    });

	  this.contentWidth = this.content.getContentDimensions().contentWidth;

    document.getElementById("fundLeft").onscroll = function () {
      document.getElementById("fundRight").scrollTop = document.getElementById("fundLeft").scrollTop;
    };

    document.getElementById("fundRight").onscroll = function () {
      document.getElementById("fundLeft").scrollTop = document.getElementById("fundRight").scrollTop;
    };

    console.log(window.orientation);

    let params_showByLandscape = this.navParams.get("showByLandscape");
    console.log("params_showByLandscape", params_showByLandscape);
    if (params_showByLandscape) {
      this.disabledExistFullScreen = true;
      this.setShowByLandscape(1);
    }
  }

  ionViewDidEnter() {
	  this.loadListData();
  }

  initQueryCondition() {
	  this.queryCondition = {
      fund_code: "",
      startDate: "",
      endDate: "",
      dataStyle: "10"
    };

	  this.queryCondition.startDate = this.common.getNowFormatDate();
	  this.queryCondition.endDate = this.common.getDate(6);
    this.storage.get("userInfo").then(user => {
      this.userInfo = user;
      this.storage.get("selected_fund_cash" + this.userInfo.loginid).then(selected_fund => {
        if (selected_fund) {
          this.selectedFund = selected_fund;
          this.queryCondition.fund_code = _.map(this.selectedFund, "vc_fund_code");
        }
      });
    });
  }

  selectFund() {
    let profileModal = this.modalCtrl.create(IpmCirculateModal, {
      selectedFund: this.selectedFund
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        this.selectedFund = data;
        this.storage.set("selected_fund_cash" + this.userInfo.loginid, data);
        this.queryCondition.fund_code = _.map(this.selectedFund, "vc_fund_code");
      }
    });
    profileModal.present();
  }

	setShowQueryCondition() {
	  this.showQueryCondition = !this.showQueryCondition;
    // document.getElementById("gridRight").style.height = 60 * this.queryCondition.fund_code.length  + 34 + "px";
    this.setDataGridHeight();
	  this.content.scrollToTop();
  }

  setDataGridHeight() {
    let row = this.listData.length;
    // console.log(row);
    let colNum = 9;
    if (this.isRedemption) {
      colNum++
    }
    if (document.getElementById("CashDetailGridTitle")) {
      document.getElementById("CashDetailGridTitle").style.width = 200 * colNum + "px";
    }
    if (document.getElementById("CashDetailGridRight")) {
      document.getElementById("CashDetailGridRight").style.height = 60 * (row + 1) + 60 + "px";
    }

    let params_showByLandscape = this.navParams.get("showByLandscape");
    if (params_showByLandscape) {
      this.showByLandscape = false;
      this.setShowByLandscape(1);
    }
  }

  /**
   * [loadListData 加载列表数据]
   */
  loadListData() {
    this.cashService.getCashTARedemptionDetail(this.params).subscribe(returnDatas => {
      console.log("#######", returnDatas);
      if (returnDatas) {
        this.listData = returnDatas;

        _.forEach(this.listData, data => {
          data["en_balance"] = this.common.formatNumberToAccountancy2(data["en_balance"], null);
          data["l_quantity"] = this.common.formatNumberToAccountancy2(_.toString(parseFloat(data["l_quantity"]).toFixed()), null);
        });

        if (this.listData.length <= 0) {
          this.isLoadMore = false;
        }

        this.setDataGridHeight();
      } else {
        this.isLoadMore = false;
        this.setDataGridHeight();
      }
    });
  }



  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.pageIndex != 1) {
      console.info("-----------infiniteScroll------------");
      console.info(infiniteScroll);
      if (this.isLoadMore) {
        // this.loadListData(this.pageIndex, infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.pageIndex = 1;
    this.isLoadMore = true;
    // this.loadListData(this.pageIndex, null, refresher);
  }

  goPos() {
    let offsetHeight = document.getElementById("inputEnValue").offsetHeight;
    if (this.plt.is("android")) {
      console.log(offsetHeight);
      this.content.scrollTo(0, offsetHeight * 5);
    }
  }

  formatNumberToAccountancy(target) {
    let result = "";
    if (target) {
      let fix = "";
      if (target.indexOf("-") > -1) {
        fix = "-";
        target = _.replace(target, "-", "");
      }
      let temp = target.split(".");
      if (temp[0]) {
        let length = temp[0].length;
        let remainder = length % 3;
        let mark = remainder == 0 ? remainder : remainder - 1;
        for (var i = length - 3; i > mark; i -=3 ) {
          result = "," + temp[0].substr(i, 3) + result;
        }
        result = fix + temp[0].substr(0, remainder == 0 ? 3 : remainder) + result;
        if (temp[1]) {
          result = result + "." + temp[1].substr(0, 2);
          if (temp[1].length == 1) {
            result = result + "." + temp[1] + "0";
          }
        } else {
          result = result + ".00";
        }
      }
    }
    return result;
  }

  /**
   * 切换横竖屏
   */
  setShowByLandscape(type) {
    if (!this.showByLandscape && type === 2) {
      return false
    }
    this.showByLandscape = !this.showByLandscape;
    if (this.showByLandscape) {
      if (this.disabledExistFullScreen === false) {
        this.plt.ready().then(() => {
          if (this.showByLandscape == true) {
            this.statusBar.hide();
          }
        });
      }

      let child = document.getElementById("cashDetailContent").getElementsByClassName("scroll-content")[0];
      child["style"]["-webkit-transform"] = "rotate(90deg)";
      child["style"]["-webkit-transform-origin"] = "top";
      child["style"].height = this.contentWidth + "px";
      child["style"].width = document.getElementById("cashDetailContent").offsetHeight + "px";
      child["style"].zIndex = "99999";
      this.scrollContentMarginTop = child["style"].marginTop;
      child["style"].marginTop = document.getElementById("cashDetailContent").offsetHeight / 2 + "px";
      child["style"].marginLeft = (this.contentWidth - document.getElementById("cashDetailContent").offsetHeight / 2) + "px";

      document.getElementById("cashDetailFundLeft").style.height = this.contentWidth + "px";
      document.getElementById("cashDetailFundRight").style.height = this.contentWidth + "px";
      document.getElementById("cashDetailFundRight").style.marginTop = 0 - this.contentWidth + "px";
      document.getElementById("cashDetailFundLeft").style.maxWidth = "20%";
      document.getElementById("cashDetailFundRight").style.maxWidth = "80%";
      document.getElementById("cashDetailFundRight").style.width = "80%";
      document.getElementById("cashDetailFundRight").style.marginLeft = "20%";

      let cashDetailContent = document.getElementById("cashDetailContent").offsetHeight;
      document.getElementById("dataRow").style.width = cashDetailContent - 10 + "px";

    } else {
      if (this.disabledExistFullScreen === false) {
        this.plt.ready().then(() => {
          if (this.showByLandscape == false) {
            this.statusBar.show();
          }
        });
      }

      let child = document.getElementById("cashDetailContent").getElementsByClassName("scroll-content")[0];
      child["style"]["-webkit-transform"] = "rotate(0deg)";
      child["style"].marginTop = this.scrollContentMarginTop;
      child["style"].marginBottom = "0px";
      child["style"].height = "auto";
      child["style"].width = "auto";
      child["style"].marginLeft = "0px";

      document.getElementById("dataRow").style.width = this.contentWidth + "px";
      document.getElementById("cashDetailFundLeft").style.height = this.fundLeftHeight + "px";
      document.getElementById("cashDetailFundRight").style.height = this.fundRightHeight + "px";
      document.getElementById("cashDetailFundRight").style.marginTop = "0";
      document.getElementById("cashDetailFundLeft").style.maxWidth = "33%";
      document.getElementById("cashDetailFundRight").style.maxWidth = "67%";
      document.getElementById("cashDetailFundRight").style.marginLeft = "33%";

    }
  }

  scrollHandler(e) {

  }

  existPage() {
    this.showByLandscape = !this.showByLandscape;
    document.getElementById("existPage").style.display = "none";
    this.navCtrl.pop();
  }

}

